<template>
  <div class="statisticsSz">
    <div class="content">
      <CustomTable
        ref="JTable"
        height="420"
        :row-class-name="rowClassName"
        :isAutoLoad="false"
        :isPages="false"
        :border="true"
        :columns="columns"
        @on-cell-click="handleCellClick"  />
    </div>

    <div class="content">
      <CustomTable
        v-if="isTownShow"
        ref="JTableZhen"
        height="420"
        :row-class-name="rowClassName"
        :isAutoLoad="false"
        :isPages="false"
        :border="true"
        :columns="columnsZhen"  />
    </div>
  </div>
</template>

<script>
import { areaList, townList  } from 'common/js/modules'
import { sourceList, columns, townColumns} from './js/modules'
import { mapActions, mapState } from 'vuex'

export default {
  computed: {
    isArea ({ searchValue }) {
      return searchValue.area
    },
    currentTown ({ isArea, townList, searchValue }) {
      if (!isArea) {
        return []
      }

      const arr = []

      townList.map(item => {
        if (item.value.indexOf(searchValue.area) > -1) {
          arr.push(item.label)
        }
      })

      return arr
    },
    selectedDistrict ({ areaList, searchValue }) {
      const obj = areaList.find(item => item.value === searchValue.area) || {};
      return obj.label;
    },
    countTitle({ isArea, selectedDistrict }) {
      if (!isArea) {
        return '各区水闸工程及测站数量统计';
      } else {
        return `${selectedDistrict}各镇街水闸工程及测站数量统计`;
      }
    },
    statusTitle({ isArea, selectedDistrict }) {
      if (!isArea) {
        return '各区水闸测站状态统计';
      } else {
        return `${selectedDistrict}各镇街水闸测站状态统计`;
      }
    },
    ...mapState({
      total: state => state.statisticsSz.total,
      totalObj: state => state.statisticsSz.totalObj
    })
  },
  created () {
    this.columns = columns()
    this.townColumns = townColumns()
    this.areaList = areaList()
    this.townList = townList()
    this.sourceList = sourceList()
    this.initContentHeight()
    window.addEventListener('resize', this.handleResize)
    this._getData()
  },
  data () {
    return {
      statusValue: '全部',
      searchValue: {
        name: '',
        area: ''
      },
      contentHeight: 600,
      countChart: null,
      statusChart: null,
      columnsZhen: [],
      isTownShow: false
    }
  },
  mounted () {
    // 渲染状态统计图表
    // this.$nextTick(() => {
    //   this.refreshData()
    // });
  },
  methods: {
    refreshData () {
      // this.GET_DATA()
      this.updateChart()
    },
    updateChart () {
      this.updateCountChart()
      this.updateStatusChart();
    },
    initContentHeight () {
      this.contentHeight = window.innerHeight - 150
    },
    handleResize () {
      this.initContentHeight()
      // 重新调整图表大小
      if (this.countChart) {
        this.countChart.resize();
      }
      if (this.statusChart) {
        this.statusChart.resize();
      }
    },
    handleCellClick (row, column) {
      const title = column ? column.title : '禅城区'
      this.isTownShow = false
      this.columnsZhen = this.townColumns[title]

      this.$nextTick(() => {
        this.isTownShow = true
        
        setTimeout(() => {
          this.$refs.JTableZhen.tableData = this.totalObj[title]['townArr']
        }, 20)
      })
    },
    rowClassName (row) {
      const status = row.tjName
      let color = ''

      // 根据状态设置不同颜色
      if (status === '水情正常' || status === '工情正常' || status === '视频全部在线') {
        color = 'tbBgGreen'
      } else if (status === '水情延迟' || status === '视频部分在线') {
        color = 'tbBgOrgen'
      } else {
        color = 'tbBgRed'
      }
        return color
    },
    updateCountChart() {
      if (this.isArea) {
        this.generateCountTownData();
      } else {
        this.generateCountDistrictData();
      }
    },
    generateCountDistrictData() {
      const xArr = [];
      const engineeringData = [];
      const stationData = [];
      
      this.areaList.map(item => {
        xArr.push(item.label);
        const engineeringCount = Math.floor(Math.random() * 100) + 50;
        const stationCount = Math.floor(Math.random() * 200) + 100;
        
        engineeringData.push(engineeringCount);
        stationData.push(stationCount);
      });
      
      this.renderCountChart(xArr, { engineeringData, stationData });
    },
    generateCountTownData() {
      if (!this.isArea) {
        return;
      }
      
      const engineeringData = [];
      const stationData = [];
      
      this.currentTown.map(item => {
        const engineeringCount = Math.floor(Math.random() * 50) + 10;
        const stationCount = Math.floor(Math.random() * 100) + 20;
        
        engineeringData.push(engineeringCount);
        stationData.push(stationCount);
      });
      
      this.renderCountChart(this.currentTown, { engineeringData, stationData });
    },
    renderCountChart(xArr, yArr) {
      // 如果已有图表实例，先销毁
      if (this.countChart) {
        this.countChart.dispose();
      }
      
      // 创建新的图表实例
      this.countChart = echarts.init(this.$refs.countChart);
      
      const option = {
        title: {
          text: this.countTitle
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
        },
        legend: {
          data: ['工程数量', '测站数量'],
          right: '1%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xArr
          }
        ],
        yAxis: [
          {
            type: 'value',
            minInterval: 1
          }
        ],
        series: [
          {
            name: '工程数量',
            type: 'bar',
            barGap: 0,
            data: yArr.engineeringData,
            itemStyle: {
              color: 'rgba(64, 158, 255, 0.8)'
            }
          },
          {
            name: '测站数量',
            type: 'bar',
            data: yArr.stationData,
            itemStyle: {
              color: 'rgba(103, 194, 58, 0.8)'
            }
          }
        ]
      };
      
      this.countChart.setOption(option);
    },
    updateStatusChart() {
      if (this.isArea) {
        this.generateStatusTownData();
      } else {
        this.generateStatusDistrictData();
      }
    },
    generateStatusDistrictData() {
      const xArr = [];
      const sqzcData = [];
      const sqycData = [];
      const sqqsData = [];
      const gqzcData = [];
      const gqqsData = [];
      const spzxData = [];
      const spbfzxData = [];
      const splxData = [];
      
      this.areaList.map(item => {
        xArr.push(item.label);
        const sqzcCount = Math.floor(Math.random() * 50) + 30;
        const sqycCount = Math.floor(Math.random() * 50) + 30;
        const sqqsCount = Math.floor(Math.random() * 50) + 30;
        const gqzcCount = Math.floor(Math.random() * 50) + 30;
        const gqqsCount = Math.floor(Math.random() * 50) + 30;
        const spzxCount = Math.floor(Math.random() * 50) + 30;
        const spbfzxCount = Math.floor(Math.random() * 50) + 30;
        const splxCount = Math.floor(Math.random() * 50) + 30;
        
        sqzcData.push(sqzcCount);
        sqycData.push(sqycCount);
        sqqsData.push(sqqsCount);
        gqzcData.push(gqzcCount);
        gqqsData.push(gqqsCount);
        spzxData.push(spzxCount);
        spbfzxData.push(spbfzxCount);
        splxData.push(splxCount);
      });
      
      this.renderStatusChart(xArr, { sqzcData, sqycData, sqqsData, gqzcData, gqqsData, spzxData, spbfzxData, splxData });
    },
    generateStatusTownData() {
      if (!this.isArea) {
        return;
      }
      
      const sqzcData = [];
      const sqycData = [];
      const sqqsData = [];
      const gqzcData = [];
      const gqqsData = [];
      const spzxData = [];
      const spbfzxData = [];
      const splxData = [];
      
      this.currentTown.map(item => {
        const sqzcCount = Math.floor(Math.random() * 50) + 30;
        const sqycCount = Math.floor(Math.random() * 50) + 30;
        const sqqsCount = Math.floor(Math.random() * 50) + 30;
        const gqzcCount = Math.floor(Math.random() * 50) + 30;
        const gqqsCount = Math.floor(Math.random() * 50) + 30;
        const spzxCount = Math.floor(Math.random() * 50) + 30;
        const spbfzxCount = Math.floor(Math.random() * 50) + 30;
        const splxCount = Math.floor(Math.random() * 50) + 30;
        
        sqzcData.push(sqzcCount);
        sqycData.push(sqycCount);
        sqqsData.push(sqqsCount);
        gqzcData.push(gqzcCount);
        gqqsData.push(gqqsCount);
        spzxData.push(spzxCount);
        spbfzxData.push(spbfzxCount);
        splxData.push(splxCount);
      });
      
      this.renderStatusChart(this.currentTown, { sqzcData, sqycData, sqqsData, gqzcData, gqqsData, spzxData, spbfzxData, splxData });
    },
    renderStatusChart(xArr, yArr) {
      // 如果已有图表实例，先销毁
      if (this.statusChart) {
        this.statusChart.dispose();
      }
      
      // 创建新的图表实例
      this.statusChart = echarts.init(this.$refs.statusChart);
      
      const option = {
        title: {
          text: this.statusTitle
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          type: 'scroll',
          data: ['水情正常', '水情延迟', '水情缺失', '工情正常', '工情缺失', '视频在线', '视频部分在线', '视频离线'],
          right: '1%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xArr
          }
        ],
        yAxis: [
          {
            type: 'value',
            minInterval: 1
          }
        ],
        series: [
          {
            name: '水情正常',
            type: 'bar',
            stack: '水情',
            data: yArr.sqzcData,
            itemStyle: {
              color: '#19be6b'
            },
            label: {
              show: true,
              position: 'top'
            }
          },
          {
            name: '水情延迟',
            type: 'bar',
            stack: '水情',
            data: yArr.sqycData,
            itemStyle: {
              color: '#ff9900'
            }
          },
          {
            name: '水情缺失',
            type: 'bar',
            stack: '水情',
            data: yArr.sqqsData,
            itemStyle: {
              color: '#ed4014'
            }
          },
          {
            name: '工情正常',
            type: 'bar',
            stack: '工情',
            data: yArr.gqzcData,
            itemStyle: {
              color: '#2d8cf0'
            }
          },
          {
            name: '工情缺失',
            type: 'bar',
            stack: '工情',
            data: yArr.gqqsData,
            itemStyle: {
              color: '#ff6600'
            }
          },
          {
            name: '视频在线',
            type: 'bar',
            stack: '视频',
            data: yArr.spzxData,
            itemStyle: {
              color: '#19be6b'
            }
          },
          {
            name: '视频部分在线',
            type: 'bar',
            stack: '视频',
            data: yArr.spbfzxData,
            itemStyle: {
              color: '#ff9900'
            }
          },
          {
            name: '视频离线',
            type: 'bar',
            stack: '视频',
            data: yArr.splxData,
            itemStyle: {
              color: '#ed4014'
            }
          }
        ]
      };
      
      this.statusChart.setOption(option);
    },
    async _getData () {
      const res = await this.GET_DATA()

      this.$refs.JTable.tableData = this.total

      this.handleCellClick()
    },
    ...mapActions({
      'GET_DATA': 'statisticsSz/GET_DATA'
    })
  },
  beforeDestroy () {
    // 销毁图表实例
    if (this.countChart) {
      this.countChart.dispose();
    }
    if (this.statusChart) {
      this.statusChart.dispose();
    }
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

<style lang="scss" scoped>
.statisticsSz {
  width: 100%;
  height: 100%;
  position: relative;
  box-sizing: border-box;
  padding: 15px;
  overflow: auto;
  > .content {
    width: 100%;
    height: 420px;
    position: relative;
    margin-bottom: 15px;
    &:nth-last-of-type(1) {
      margin-bottom: 0;
    }
  }
}
</style>

<style lang="scss">
.statisticsSz {
  .tbBgGreen {
    td {
      background-color: #19be6b;
      color: white;
    }
  }
  .tbBgOrgen {
    td {
      background-color: #ff9900;
      color: white;
    }
  }
  .tbBgRed {
    td {
      background-color: #ed4014;
      color: white;
    }
  }
}
</style>